<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/13
 * Time: 11:45
 */
namespace app\common\model;

use app\common\lib\exception\ApiException;
use think\Cache;

class Rectification extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_rectification';
    protected $insert = ['create_time'];
    protected $update = ['update_time'];

    public function setCreateTimeAttr($value)
    {
        return time();
    }

    public function setUpdateTimeAttr($value)
    {
        return time();
    }

    /**
     * 关联校准生辰  事件模型
     * @return \think\model\relation\HasMany
     */
    public function events()
    {
        return $this->hasMany('RectificationEvent','reid','id');
    }

    /**
     * 关联校准生辰 结果模型
     * @return \think\model\relation\HasMany
     */
    public function result()
    {
        return $this->hasMany('RectificationResult','reid','id');
    }

    public function orders()
    {
        return $this->hasOne('Orders','reid','id',[],'LEFT')->field('order_id,status,trade_type,pay_time,return_time,total_amount');
    }

    public function recode()
    {
        return $this->belongsTo('Recode','rid');
    }

    public function getRectifications($map = [])
    {
        $uid = $map['uid'];
        $page = $map['page'];

        $goods = (new Goods())->getGoodsRec(['id' => 1]);// 校准生辰商品

        if ($this->cache_on >= 1)
        {
            $goods = Cache::get('goods');

            $data = Cache::get('rectification_' . $uid);
        }

        if (empty($data))
        {
            try
            {
                // 要查询的字段
                $field = 're.id,re.status,re.start_time,re.end_time,re.create_time,or.order_id,or.trade_type,or.total_amount';
                $where = ['re.uid'=>$uid,'re.status'=>['neq',config('code.status_delete')]];
                $order = 're.id DESC';

                $data = $this->alias('re')
                    ->field($field)
                    ->join('wechat_backup_07_18_14_43_00.app_orders or','or.reid=re.id','RIGHT')
                    ->where($where)
                    ->order($order)
                    ->paginate(10,false,['page'=>$page]);
            }
            catch (\Exception $e)
            {
                return show(config('code.error'), $e->getMessage());
            }
        }




        foreach ($data as $k => $d)
        {
            $data[$k]['or_prize'] = $goods['or_prize'];

            $data[$k]['now_prize'] = $goods['now_prize'];
        }

        return $data;
    }
}
